<?php

namespace app\common\model\tyyh;

class GroupBuying extends CUBase {
    protected static function init()
    {
        parent::init();

        self::beforeInsert(function ($data) {
            if(!isset($data['puid'])) {
                $data['puid'] = 0;
            }
        	if(!isset($data['lv'])) {
        		$data['lv'] = 0;
        	}
        	return $data;
        });
    }

    //获取用户信息
    public function getUserAttr($value, $data) {
        return loadModel('tyyh\\User')->where(['id' => $data['uid']])->field('id,photo,nickname,phone')->find();
    }

    //获取用户推广单数
    public function getPromotionCountAttr($value, $data) {
        $statusArr = loadEnum('GroupBuyingPromotionStatus')->isPayStatus();
        return loadModel('tyyh\\GroupBuyingPromotion')->where(['uid' => $data['uid']])->whereIn('status', $statusArr)->count();
    }

    //下级用户数
    public function getSubNumberAttr($value, $data) {
        $count = $this->where(['puid' => $data['uid']])->count();
        return $count;
    }
    
    //获取用户单月的推广单数
    public function getPromotionCountMoonAttr($value, $data) {
        $startTimestamp = strtotime(date('Y-m-01 00:00:00'));
        $endTimestamp = strtotime(date('Y-m-t 23:59:59'));
        $statusArr = loadEnum('GroupBuyingPromotionStatus')->isPayStatus();
        return loadModel('tyyh\\GroupBuyingPromotion')->where(['uid' => $data['uid']])->whereIn('status', $statusArr)->where('createtime', 'between', [$startTimestamp, $endTimestamp])->count();
    }


    //获取上级用户信息
    public function getPUserAttr($value, $data) {
        return loadModel('tyyh\\User')->where(['id' => $data['puid']])->field('id,photo,nickname,phone')->find();
    }
}
